package com.ego.cart.service.impl;

import com.ego.cart.pojo.OrderCartPojo;
import com.ego.cart.service.CartService;
import com.ego.commons.pojo.CartPojo;
import com.ego.commons.pojo.EgoResult;
import com.ego.commons.pojo.TbItemDetails;
import com.ego.commons.utils.CookieUtils;
import com.ego.commons.utils.JsonUtils;
import com.ego.commons.utils.ServletUtil;
import com.ego.dubbo.service.TbItemDubboService;
import com.ego.pojo.TbItem;
import com.ego.pojo.TbUser;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Value("${ego.item.details.rediskey}")
    private String detailsKey;
    @Value("${ego.cart.tempcart}")
    private String tempCartKey;
    // cart:
    @Value("${ego.cart.rediskey}")
    private String cartRedisKey;
    @Reference
    private TbItemDubboService tbItemDubboService;
    @Override
    public void addCart(Long id, int num) {
        TbUser tbUser = (TbUser)ServletUtil.getRequest().getSession().getAttribute("loginUser");
        //如果用户登录
        if(tbUser!=null){
            // 第一次向redis中存储数据时
            List<CartPojo> list = new ArrayList<>();
            // 购物商品使用redis进行存储。 redis是key-value
            // 设定redis中key = cart:用户id
            String key = cartRedisKey + tbUser.getId();
            if(redisTemplate.hasKey(key)){
                list  = (List<CartPojo>) redisTemplate.opsForValue().get(key);
                // 判断当前商品是否已经存在。
                for(CartPojo cp : list){
                    // Long要用equals进行比较
                    if(cp.getId().equals(id)){
                        // 如果存在修改数量
                        cp.setNum(cp.getNum()+num);
                        redisTemplate.opsForValue().set(key,list);
                        return;
                    }
                }
            }

            // 创建CartPojo 购物车商品
            String detailsRedisKey = detailsKey+id;
            TbItemDetails tbItemDetails = (TbItemDetails) redisTemplate.opsForValue().get(detailsRedisKey);
            CartPojo cartPojo = new CartPojo();
            cartPojo.setId(tbItemDetails.getId());
            cartPojo.setImages(tbItemDetails.getImages());
            cartPojo.setNum(num);
            cartPojo.setPrice(tbItemDetails.getPrice());
            cartPojo.setTitle(tbItemDetails.getTitle());
            list.add(cartPojo);
            redisTemplate.opsForValue().set(key,list);
            return ;
        }
        // 如果用户没有登录
        Map<Long,CartPojo> tempCart = new HashMap<>();
        // 第一次操作：cookie中没有任何数据时，
        String cookieValue = CookieUtils.getCookieValueBase64(ServletUtil.getRequest(), tempCartKey);
        if(Strings.isNotEmpty(cookieValue)){// 当前Cookie已经存在临时购物车商品
            // 判断是否已经存在当前商品
            tempCart = JsonUtils.jsonToMap(cookieValue, Long.class, CartPojo.class);
            if(tempCart.containsKey(id)){
                // 如果存在，只需要修改商品数量
                CartPojo cartPojo = tempCart.get(id);
                cartPojo.setNum(cartPojo.getNum()+num);
                CookieUtils.doSetCookieBase64(ServletUtil.getRequest(),ServletUtil.getResponse(),tempCartKey, JsonUtils.objectToJson(tempCart),2592000);
                return;
            }
        }
        // 创建CartPojo 购物车商品
        String key = detailsKey+id;
        TbItemDetails tbItemDetails = (TbItemDetails) redisTemplate.opsForValue().get(key);
        CartPojo cartPojo = new CartPojo();
        cartPojo.setId(tbItemDetails.getId());
        cartPojo.setImages(tbItemDetails.getImages());
        cartPojo.setNum(num);
        cartPojo.setPrice(tbItemDetails.getPrice());
        cartPojo.setTitle(tbItemDetails.getTitle());
        // 加入Map中
        tempCart.put(id,cartPojo);
        // 放入到临时购物车中
        CookieUtils.doSetCookieBase64(ServletUtil.getRequest(),ServletUtil.getResponse(),tempCartKey, JsonUtils.objectToJson(tempCart),2592000);
    }

    @Override
    public List<CartPojo> showCart() {
        TbUser tbUser = (TbUser) ServletUtil.getRequest().getSession().getAttribute("loginUser");
        // 用户购物车
        if(tbUser!=null){
            String key = cartRedisKey + tbUser.getId();
            List<CartPojo> list = (List<CartPojo>) redisTemplate.opsForValue().get(key);
            return list;
        }

        // 临时购物车
        List<CartPojo> list = new ArrayList<>();
        String cookieValue = CookieUtils.getCookieValueBase64(ServletUtil.getRequest(), tempCartKey);
        if(Strings.isNotEmpty(cookieValue)){
            Map<Long,CartPojo> map = JsonUtils.jsonToMap(cookieValue,Long.class,CartPojo.class);
            for(Long id : map.keySet()){
                list.add(map.get(id));
            }
        }
        return list;
    }

    @Override
    public EgoResult updateNum(Long id, int num) {

        TbUser tbUser = (TbUser) ServletUtil.getRequest().getSession().getAttribute("loginUser");
        // 用户购物车
        if(tbUser!=null){
            String key = cartRedisKey + tbUser.getId();
            List<CartPojo> list = (List<CartPojo>) redisTemplate.opsForValue().get(key);
            for(CartPojo cp : list){
                // Long要用equals
                if(cp.getId().equals(id)){
                    cp.setNum(num);
                    break;
                }
            }
            redisTemplate.opsForValue().set(key,list);
        }else{
            String cookieValue = CookieUtils.getCookieValueBase64(ServletUtil.getRequest(), tempCartKey);
            Map<Long,CartPojo> tempCart = JsonUtils.jsonToMap(cookieValue,Long.class,CartPojo.class);
            tempCart.get(id).setNum(num);
            CookieUtils.doSetCookieBase64(ServletUtil.getRequest(),ServletUtil.getResponse(),tempCartKey, JsonUtils.objectToJson(tempCart),2592000);
        }
        return EgoResult.ok();
    }

    @Override
    public EgoResult delele(Long id) {
        TbUser tbUser = (TbUser) ServletUtil.getRequest().getSession().getAttribute("loginUser");
        // 用户购物车
        if(tbUser!=null){
            String key = cartRedisKey + tbUser.getId();
            List<CartPojo> list = (List<CartPojo>) redisTemplate.opsForValue().get(key);
            for(CartPojo cp : list){
                // Long要用equals
                if(cp.getId().equals(id)){
                    list.remove(cp);
                    break;
                }
            }
            redisTemplate.opsForValue().set(key,list);
        }else {
            String cookieValue = CookieUtils.getCookieValueBase64(ServletUtil.getRequest(), tempCartKey);
            Map<Long, CartPojo> tempCart = JsonUtils.jsonToMap(cookieValue, Long.class, CartPojo.class);
            tempCart.remove(id);
            CookieUtils.doSetCookieBase64(ServletUtil.getRequest(), ServletUtil.getResponse(), tempCartKey, JsonUtils.objectToJson(tempCart), 2592000);
        }
        return EgoResult.ok();
    }

    @Override
    public List<OrderCartPojo> showOrderCart(List<Long> ids) {
        List<OrderCartPojo> listResult = new ArrayList<>();
        TbUser tbUser = (TbUser) ServletUtil.getRequest().getSession().getAttribute("loginUser");
        String key = cartRedisKey + tbUser.getId();
        // 取出用户购物车数据
        List<CartPojo> list = (List<CartPojo>) redisTemplate.opsForValue().get(key);
        for(Long id : ids){
            for(CartPojo cp : list){
                if(cp.getId().equals(id)){
                    OrderCartPojo ocp = new OrderCartPojo();
                    BeanUtils.copyProperties(cp,ocp);
                    // 比较购物车中商品数量和数据库中商品数量
                    TbItem tbItem = tbItemDubboService.selectById(id);
                    if(tbItem.getNum()>=cp.getNum()){
                        ocp.setEnough(true);
                    }else{
                        ocp.setEnough(false);
                    }
                    listResult.add(ocp);
                    break;
                }
            }
        }

        return listResult;
    }

    @Override
    public int deleteUsercartByItemid(Long userId, Long [] ids) {
        try {
            String key = cartRedisKey + userId;
            List<CartPojo> userCart = (List<CartPojo>) redisTemplate.opsForValue().get(key);
            for(Long id : ids){
                for(CartPojo cp : userCart){
                    if(cp.getId().equals(id)){
                        userCart.remove(cp);
                        break;
                    }
                }
            }
            redisTemplate.opsForValue().set(key,userCart);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

}
